package geez.widget;

import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.user.client.ui.FocusListener;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.TextBox;

import static geez.widget.Geez.withStyle;

public class GTextBox<T extends GTextBox> extends TextBox implements GChangable, GFocusable {

    public T id(String id) {
        Geez.withNameAndId(this, id);
        return downcastSelf();
    }

    public T name(String name) {
        setName(name);
        return downcastSelf();
    }

    public T css(String cssClass, String... optionalClasses) {
        withStyle(this, cssClass, optionalClasses);
        return downcastSelf();
    }

    public GTextBox enable() {
        setEnabled(true);
        return this;
    }

    public GTextBox disable() {
        setEnabled(false);
        return this;
    }

    public T maxLength(int length) {
        setMaxLength(length);
        return downcastSelf();
    }

    public T tabIndex(int index) {
        setTabIndex(index);
        return downcastSelf();
    }

    public T text(String text) {
        setText(text);
        return downcastSelf();
    }

    public T enableAndShow(boolean value) {
        setEnabled(value);
        return makeVisible(value);
    }

    public T hide() {
        return makeVisible(false);
    }

    public T show() {
        return makeVisible(true);
    }

    @Deprecated
    public T withFocusListener(FocusListener focusListener) {
        addFocusListener(focusListener);
        return downcastSelf();
    }

    @Deprecated
    public T withKeyboardListener(KeyboardListenerAdapter keyboardListener) {
        addKeyboardListener(keyboardListener);
        return downcastSelf();
    }

    private T makeVisible(boolean visible) {
        setVisible(visible);
        return downcastSelf();
    }

    private T downcastSelf() {
        return (T) this;
    }

    public GTextBox add(ChangeHandler handler) {
        addChangeHandler(handler);
        return this;
    }

    public GTextBox add(FocusHandler handler) {
        addFocusHandler(handler);
        return this;
    }

    public GTextBox add(BlurHandler handler) {
        addBlurHandler(handler);
        return this;
    }

    public GTextBox focus() {
        setFocus(true);
        return this;
    }
}
